package sskj.regulatory.presentation.screen.registeCaptcha

import android.view.View
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.vondear.rxtools.RxKeyboardTool
import com.vondear.rxtools.view.RxToast
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_register_captcha.view.*
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import sskj.regulatory.R
import sskj.regulatory.domain.entity.user.UserEntity
import sskj.regulatory.presentation.base_mvp.base.BaseFragment
import sskj.regulatory.presentation.screen.register.*
import sskj.regulatory.presentation.screen.registerMakePas.RegisteMakePasFragment
import sskj.regulatory.presentation.utils.delegates.bundle
import sskj.regulatory.presentation.widget.VerificationCodeInput
import sskj.regulatory.ribble.presentation.utils.extensions.log
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class RegisterCaptchaFragment : BaseFragment<RegisterContract.View, RegisterContract.Presenter>(), RegisterContract.View {

    private val TAG = "RegisterCaptchaFragment"

    private var isShow: Boolean = false

    companion object {
        var along: Long? = 1L
    }

    val userEntity: UserEntity by bundle()

    @Inject
    lateinit var mPresenter: RegisterPresenter

    override fun injectDependencies() = activityComponent.inject(this)

    override fun initPresenter() = mPresenter

    override val layoutResId: Int = R.layout.fragment_register_captcha

    var mSubscription: Subscription? = null // Subscription 对象，用于取消订阅关系，防止内存泄露

    override fun onBackPressed(): Boolean = true

    override fun initView() {
        mCacheView.vCodeInput.clearAllText()
        mCacheView.messageTv.visibility = View.GONE
        initTopBar()
        initEvent()
        vCodeTimer()
    }

    private fun initTopBar() {
        mCacheView.rcTopBar.addLeftBackImageButton().setOnClickListener {
            popBackStack()
        }
    }

    private fun initEvent() {
        mCacheView.vCodeInput.setInputCompleteListener(object : VerificationCodeInput.InputCompleteListener {
            override fun inputComplete() {
                if (mCacheView.vCodeInput.textContent.length === 6) {
                    when (mCacheView.vCodeInput.textContent) {
                        userEntity.vCode -> {
                            RxKeyboardTool.hideSoftInput(getActivity())
                            mCacheView.registeNextButton.isEnabled = true
                            mCacheView.registeNextButton.setBackgroundResource(R.drawable.bg_btn_login_selected)
                        }
                        else -> {

                            mCacheView.vCodeInput.clearAllText()
                            mCacheView.messageTv.visibility = View.VISIBLE
                        }
                    }
                } else {
                    mCacheView.messageTv.visibility = View.GONE
                }
            }

            override fun deleteContent() {

            }
        })

        mCacheView.timeNum.setOnClickListener {
            mPresenter.sendVCode(userEntity.phone)
        }

        mCacheView.registeNextButton.setOnClickListener {
            var registeMakePasFragment = RegisteMakePasFragment()
            registeMakePasFragment.arguments = RegisterFragment.getBundle(userEntity)
            startFragment(registeMakePasFragment)
        }

    }

    override fun showError(message: String?) {
        QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("错误提示")
                .setMessage(message)
                .addAction("确定") { dialog, _ -> dialog.dismiss() }
                .create(R.style.QMUI_Dialog).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        isShow = false
    }

    override fun onResume() {
        super.onResume()
        isShow = true
    }


    private fun vCodeTimer() {
        val count = 59L
        Flowable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .onBackpressureBuffer()//加上背压策略
                .take(count) //设置循环次数
                .map {
                    count - it //
                }
                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                .subscribe(object : Subscriber<Long> {
                    override fun onSubscribe(s: Subscription?) {
                        mCacheView.timeNum.isEnabled = false//在发送数据的时候设置为不能点击
                        mSubscription = s
                        s?.request(Long.MAX_VALUE)//设置请求事件的数量，重要，必须调用
                    }

                    override fun onNext(aLong: Long?) {
                        mCacheView.timeNum.text = "$aLong 秒后重新发送" //接受到一条就是会操作一次UI
                        along = aLong!!
                    }

                    override fun onComplete() {
                        if (isShow) {
                            mCacheView.timeNum.text = "【重新发送】"
                            mCacheView.timeNum.isEnabled = true
                        }
                        mSubscription?.cancel()//取消订阅，防止内存泄漏
                    }

                    override fun onError(t: Throwable?) {
                        t?.printStackTrace()
                    }
                })
    }


    override fun sendOk(phone: String, vCode: String) {
        log("=======>>>>>>>$TAG:$vCode")

        activity.tipDialog?.dismiss()
        activity.tipDialog = createDialog("发送成功!", QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
        activity.tipDialog?.show()
        vCodeTimer()
        view?.postDelayed({
            activity.tipDialog?.dismiss()
            userEntity?.username = phone
            userEntity?.phone = phone
            userEntity?.vCode = vCode
            userEntity?.time = Date()
        }, 1000)
    }

    private fun createDialog(message: String, type: Int): QMUITipDialog = QMUITipDialog.Builder(context)
            .setIconType(type)
            .setTipWord(message)
            .create()

    override fun sendError(errorMessage: String?) {
        activity.tipDialog?.dismiss()
        activity.tipDialog = createDialog("发送失败!", QMUITipDialog.Builder.ICON_TYPE_FAIL)

        activity.tipDialog?.show()

        view?.postDelayed({
            activity.tipDialog?.dismiss()
        }, 1000)
    }

    override fun sendLoading() {
        activity.tipDialog = createDialog("发送中", QMUITipDialog.Builder.ICON_TYPE_LOADING)
        activity.tipDialog?.show()
    }

    override fun sendTimeNo() = QMUIDialog.MessageDialogBuilder(getActivity())
            .setTitle("提示信息")
            .setMessage("你还需要等待 ${RegisterCaptchaFragment.along} 秒才能再次发送。")
            .addAction("确定") { dialog, _ -> dialog.dismiss() }
            .create(R.style.QMUI_Dialog).show()


    override fun showRegisterYes() {
    }

    override fun showRegisterNo() {
    }

}